import React, { Component } from 'react';
import { Table, DatePicker, Input, message } from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import tableFilter from '../../../components/tableFilter';
import ExportBtn from '../../../components/exportBtn';
import styles from './index.less';

const { RangePicker } = DatePicker;
const { Search } = Input;
const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';

@connect(stores => ({
  systemManager: stores.systemManager
}))
@tableFilter
class OperateLogPage extends Component {
  state = {
    selectedId: [],
    timeStart: '',
    timeEnd: '',
    operateUserName: '',
    operateResourceName: '',
    pageNum: 1,
    pageSize: 10,
    operateDepts: [], // 操作人部门
    resourceTypes: [], // 操作类目
    ascOrDesc: 'desc',
    totalCount: 0,
    loading: false,
    exportLoading: false
  };

  componentDidMount() {
    this.getData();
    this.getDepData();
  }

  componentDidUpdate(prevProps) {
    const {
      location: { pathname }
    } = this.props;
    const {
      location: { pathname: prevPathname }
    } = prevProps;
    if (pathname !== prevPathname) {
      this.getData();
      this.getDepData();
    }
  }

  dateChange = (e = []) => {
    this.setState(
      {
        timeStart: e.length ? e[0].startOf('day').format(DATE_TIME_FORMAT) : undefined,
        timeEnd: e.length ? e[1].endOf('day').format(DATE_TIME_FORMAT) : undefined,
        pageNum: 1
      },
      () => {
        this.getData();
        this.getDepData();
      }
    );
  };

  handleTableChange = (
    e,
    { operateDeptName, operateResourceTypeName },
    sorter
  ) => {
    const { current, pageSize } = e;
    const { operateDepts, resourceTypes } = this.state;
    this.setState(
      {
        pageNum:
          (operateDeptName && operateDeptName !== operateDepts) ||
          (operateResourceTypeName && operateResourceTypeName !== resourceTypes)
            ? 1
            : current,
        pageSize,
        ascOrDesc: sorter.order && sorter.order === 'ascend' ? 'asc' : 'desc',
        operateDepts: operateDeptName || [],
        resourceTypes: operateResourceTypeName || []
      },
      () => {
        this.getData();
        // this.getDepData();
      }
    );
  };

  operateUserNameHandleSearch = e => {
    this.setState(
      {
        operateUserName: e,
        pageNum: 1
      },
      () => {
        this.getData();
        this.getDepData();
      }
    );
  };

  operateResourceNameHandleSearch = e => {
    this.setState(
      {
        operateResourceName: e,
        pageNum: 1
      },
      () => {
        this.getData();
        this.getDepData();
      }
    );
  };

  clearOperateUserName = e => {
    if (e.target.value !== '') return;
    this.setState(
      {
        operateUserName: '',
        pageNum: 1
      },
      () => {
        this.getData();
        this.getDepData();
      }
    );
  };

  clearOperateResourceName = e => {
    if (e.target.value !== '') return;
    this.setState(
      {
        operateResourceName: '',
        pageNum: 1
      },
      () => {
        this.getData();
        this.getDepData();
      }
    );
  };

  // 操作类目名称转换

  getTypeName = (value = 0) => {
    const {
      systemManager: { operateTypeFilter }
    } = this.props;
    const temp = operateTypeFilter.find(k => Number(k.value) === value);
    return temp ? temp.text : '';
  };
  // 获取操作人部门列表

  getDepData = () => {
    const { dispatch } = this.props;
    const {
      timeStart,
      timeEnd,
      operateUserName,
      operateResourceName,
      resourceTypes,
      operateDepts,
      ascOrDesc
    } = this.state;
    const params = {
      timeStart,
      timeEnd,
      operateUserName,
      operateResourceName,
      resourceTypes,
      operateDepts,
      ascOrDesc
    };

    dispatch({
      type: 'systemManager/fetchOperateDepList',
      payload: { ...params }
    });
    dispatch({
      type: 'systemManager/fetchOperateTypeList',
      payload: { ...params }
    });
  };

  // 获取展示数据、查询、过滤、排序

  getData = () => {
    const {
      timeStart,
      timeEnd,
      operateUserName,
      operateResourceName,
      resourceTypes,
      operateDepts,
      ascOrDesc,
      pageNum,
      pageSize
    } = this.state;
    const { dispatch } = this.props;
    this.setState({
      loading: true
    });
    const params = {
      timeStart,
      timeEnd,
      operateUserName,
      operateResourceName,
      resourceTypes, // 操作类目
      operateDepts, // 操作人部门
      ascOrDesc,
      pageNum,
      pageSize
    };
    const { location } = this.props;
    const split = location.pathname.split('/');
    if (split[2] === 'systemMessage') {
      params.modules = [1];
    } else {
      params.modules = [2];
    }
    dispatch({
      type: 'systemManager/fetchOperateLogList',
      payload: { ...params }
    }).then(totalCount => {
      this.setState({
        totalCount,
        loading: false
      });
    });
  };

  // 导出excel
  exportExcel = type => {
    const {
      dispatch,
      systemManager: { operateLogList = [] } = {}
    } = this.props;
    const {
      selectedId,
      operateUserName,
      operateResourceName,
      ascOrDesc,
      resourceTypes,
      operateDepts,
      timeStart,
      timeEnd
    } = this.state;
    if (operateLogList.length <= 0) {
      message.error('当前没有导出内容', 1);
      return;
    }
    if (type !== 'all' && selectedId.length <= 0) {
      message.error('请选择需要导出的内容', 1);
      return;
    }
    this.setState({
      exportLoading: true
    });
    const payload = {
      timeStart,
      timeEnd,
      operateUserName,
      operateResourceName,
      ascOrDesc,
      resourceTypes, // 操作类目
      operateDepts, // 操作人部门
      pageNum: 1,
      pageSize: 10000,
      modules: [1],
      operateIds: type === 'all' ? [] : selectedId
    };

    dispatch({
      type: 'systemManager/exportOperateExcel',
      payload
    }).then(() => {
      this.setState({
        exportLoading: false
      });
    });
  };

  handleDisabledDate = current => current < moment().subtract(6, 'months');

  render() {
    const {
      systemManager: {
        operateLogList = [],
        operateDepFilter = [],
        operateTypeFilter = []
      },
      getColumnSearchProps = () => {}
    } = this.props;
    const { loading, pageNum, totalCount, exportLoading } = this.state;
    const rowSelection = {
      onChange: selectedRowKeys => {
        this.setState({
          selectedId: selectedRowKeys
        });
      }
    };
    const columns = [
      {
        title: '操作时间',
        dataIndex: 'operateTime',
        sorter: true,
        defaultSortOrder: 'descend',
        render: text =>
          text ? moment(text).format(DATE_TIME_FORMAT) : '---'
      },
      {
        title: '操作人姓名',
        dataIndex: 'operateUserName'
      },
      {
        title: '操作人部门',
        dataIndex: 'operateDeptName',
        filters: operateDepFilter,
        filterMultiple: false,
        ...getColumnSearchProps(operateDepFilter)
      },
      {
        title: '操作类目',
        dataIndex: 'operateResourceTypeName',
        filters: operateTypeFilter,
        filterMultiple: false,
        render: text => text || '暂无'
      },
      {
        title: '操作详情',
        dataIndex: 'details',
        render: text => <span title={text}>{text}</span>
      }
    ];
    return (
      <div className={styles.root}>
        <div className={styles.titleBox}>操作日志</div>
        <div style={{ padding: '24px' }}>
          <div className={styles.topSearch}>
            <ExportBtn
              exportExcel={type => this.exportExcel(type)}
              loading={exportLoading}
            />
            <div
              style={{
                fontSize: 14,
                color: 'rgba(0,0,0,0.85)',
                display: 'flex',
                alignItems: 'center',
                marginLeft: '16px'
              }}>
              操作时间：
              <RangePicker
                style={{ width: 224, marginRight: 21 }}
                onChange={this.dateChange}
                disabledDate={this.handleDisabledDate}
              />
              <Search
                placeholder='操作人姓名'
                style={{ width: 272, marginRight: 21 }}
                onSearch={this.operateUserNameHandleSearch}
                allowClear
                onChange={this.clearOperateUserName}
              />
              <Search
                placeholder='操作内容'
                style={{ width: 272 }}
                onSearch={this.operateResourceNameHandleSearch}
                allowClear
                onChange={this.clearOperateResourceName}
              />
            </div>
          </div>
          <Table
            style={{ background: '#fff' }}
            locale={{ emptyText: '暂无数据！' }}
            rowKey={record => record.operateId}
            columns={columns}
            dataSource={operateLogList}
            size='middle'
            rowSelection={rowSelection}
            onChange={(e, filters, sorter) =>
              this.handleTableChange(e, filters, sorter)
            }
            loading={loading}
            pagination={{
              defaultPageSize: 10,
              showQuickJumper: true,
              showSizeChanger: true,
              current: pageNum,
              total: totalCount,
              showTotal: total => `共有 ${total} 条`
            }}
          />
        </div>
      </div>
    );
  }
}

export default OperateLogPage;
